package day0507;

import java.sql.*;

/**
 * User: Allen Zhang
 * Date: 2019-05-07
 * Time: 17:05
 * 这是单线程的情况
 */
public class UnlockTest {

    //
    static String url = "jdbc:mysql://www.vm.com:3306/test?characterEncoding=utf-8&useSSL=false";
    static Connection conn = null;
    static Statement stmt=null;
    public static void main(String[] args) throws Exception {
      int num  =5;
      //
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(url,"root","root");
      conn.setAutoCommit(false);

      int amount = getAmount();
      //库存足够
      if(amount >=num){

          try {
              addOrder(num);//下订单
              updateAmount(num);//减库存
              conn.commit();
          } catch (Exception e) {
              e.printStackTrace();
              conn.rollback();//回滚
          }

      }else{
          System.out.println("库存不足,召唤师");
      }
      conn.close();
    }

    /**
     * 查库存
     * @return
     * @throws SQLException
     */
    public static int getAmount() throws SQLException {

        String amountSql = "select amount from goods where id=1";

        stmt = conn.createStatement();
        //查库存
        ResultSet rs = stmt.executeQuery(amountSql);
        int amount = 0;
        if(rs.next()){

            amount = rs.getInt(1);
        }
        rs.close();
        return amount;
    }

    /**
     * 添加订单
     * @return
     * @throws SQLException
     */
    public static int addOrder(int num) throws Exception {
        String sorderSql = "insert into goods_order(amount,name) " +
                "values("+num+",'"+Thread.currentThread().getName()+"')";
        stmt = conn.createStatement();
        int res = stmt.executeUpdate(sorderSql);
        if(res <=0){
            throw new Exception("添加订单失败");
        }
        stmt.close();
        return res;
    }

    /**
     * 修改数量
     * @return
     * @throws SQLException
     */
    public static int updateAmount(int num) throws Exception {
        String updateSql = "update goods set amount = amount-"+num+" where id=1";
        stmt = conn.createStatement();
        int res = stmt.executeUpdate(updateSql);
        stmt.close();//关闭资源放哪里都行吗？
        if (res <=0){
            throw new Exception("更新库存失败");
        }
        return res;
    }
}
